#include <iostream>
#include <queue>
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode *next;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class invertTree {
public:
    TreeNode *invert(TreeNode *root) {
        if (root == nullptr)
            return nullptr;
        // 按前序遍历顺序交换左右子树
        swap(root->left, root->right);
        invert(root->left);
        invert(root->right);
        return root;
    }
};

class treeToList {
public:
    // 树->链表：左右子树变链表---左子树为null，右子树为左子树---左子树链接在右子树
    void flatten(TreeNode *root) {
        if (root == nullptr) 
            return
        // step 1
        flatten(root->left);
        flatten(root->right);
        // step 2
        TreeNode *left = root->left;
        TreeNode *right = root->right;
        root->left = nullptr;
        root->right = left;

        // step 3
        TreeNode *cur = root;
        while (cur->right != nullptr)
            cur = cur->right;
        cur->right = right;
    };
};

class treePlusNext {
public:
    TreeNode *connect(TreeNode *root) {
        connectTwoNodes(root->left, root->right);
        return root;
    }

    void connectTwoNodes(TreeNode *node1, TreeNode *node2) {
        if (node1 == nullptr || node2 == nullptr)
            return;
        
        // 连接node1和node2
        node1->next = node2;
        // 前序遍历连接1和2
        connectTwoNodes(node1->left, node1->right);
        connectTwoNodes(node2->left, node2->right);
        // 连接node1->right和node2->left
        connectTwoNodes(node1->right, node2->left);
    }

    TreeNode *connectNotRecursive(TreeNode *root) {
        if (root == nullptr)
            return nullptr;
        // 层序遍历，对每一层单独操作
        queue<TreeNode *> q;
        q.push(root);

        while (!q.empty()) {
            int size = q.size();
            TreeNode *firstNode = q.front();
            for (int i = 0; i < size; i++) {
                TreeNode *cur = q.front();
                q.pop();
                if (cur->left)
                    q.push(cur->left);
                if (cur->right)
                    q.push(cur->right);

                firstNode->next = cur;
                firstNode = firstNode->next;
            }
            firstNode->next = nullptr;
        }
        return root;
    }
};